package com.xdy.reggie.controller;

import com.xdy.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.file-path}")
    private String filePath;

    @PostMapping("/upload")
    public R<String> uploadImage(MultipartFile file){

        try {
            String filename = file.getOriginalFilename();
            log.info("文件名称 ===> {}",filename);
            log.info("存储路径 ===> {}",filePath);

            //如果目录不存在则创建
            File dirPath = new File(filePath);
            if (!dirPath.exists()){
                dirPath.mkdirs();
            }
            //文件后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            filename = UUID.randomUUID().toString() + suffix;
            String lastFileName = filePath + filename;
            file.transferTo(new File(lastFileName));
            return R.success(filename);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("出错啦！");
        }
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            log.info("下载文件名称 ===> {}",name);
            FileInputStream fis = new FileInputStream(filePath + name);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            response.setContentType("image/jpeg");
            ServletOutputStream sos = response.getOutputStream();
            sos.write(buffer);
            sos.flush();

            //关闭资源
            sos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
